import math
import time

from django.core.paginator import Paginator

from goodsApp.collectionModel.models import Collection
from goodsApp.goodsModel.models import Goods


class CollectionService:
    ALREADY_EXISTS="商品已经存在"
    COLLECTION_SUCCESS="添加成功"

    def addGoods(self,user_id,goods_id):
        if self.__isExists(user_id=user_id,goods_id=goods_id):
            return self.ALREADY_EXISTS
        collection = Collection(uid=user_id,gid=goods_id)
        collection.save()
        return self.COLLECTION_SUCCESS

    def removeGoods(self,user_id,goods_id):
        collections = Collection.objects.filter(uid=user_id,gid=goods_id)
        if collections:
            for c in collections:
                c.delete()
    def getGoods(self,user_id,cur,size):
        col = Collection.objects.filter(uid=user_id)
        page_obj = Paginator(col,size)
        col_list = page_obj.get_page(cur).object_list
        glist = []
        for c in col_list:
            glist.append(Goods.objects.values('title','price','id','img').get(id=c.gid))
        return glist
    def getTotalGoods(self,user_id):
        num = Collection.objects.filter(uid=user_id).count()
        return math.ceil((num/10))
    def __isExists(self,user_id,goods_id):
        cset = Collection.objects.filter(uid=user_id,gid=goods_id)
        return cset!=None and len(cset)!=0